#include "../include/head.h"

int server_rmfile(const RequestPackage *prequest, char *serverDir, int netfd) {
    // 收包
    ResponsePackage response;
    bzero(&response, sizeof(response));

    char vir_path[1024] = {0};
    memcpy(vir_path, prequest->vir_path_val, prequest->vir_path_len);
    char args_path[1024] = {0};
    memcpy(args_path, prequest->args_val, prequest->args_len);
    // 查看当前工作目录是否正确
    char truePath[1024] = {0};
    int ret = snprintf(truePath, sizeof(truePath), "%s%s", serverDir, vir_path);
    if(access(truePath, F_OK)) {
        // 当前目录结构已经变更
        response.type = RES_ERR_1;
        response.vir_path_len = 0;
        strcpy(response.args_val, "当前目录结构已更改，已返回到根目录!");
        response.args_len = strlen(response.vir_path_val);
        // 这里需要分开发
        send(netfd, &response.type, sizeof(response.type), MSG_NOSIGNAL);
        send(netfd, &response.vir_path_len, sizeof(int), MSG_NOSIGNAL);
        send(netfd, &response.args_len, sizeof(int), MSG_NOSIGNAL);
        send(netfd, response.args_val, response.args_len, MSG_NOSIGNAL);

        return 0;
    }
    // 查看当前文件是否存在，这个文件可能是很复杂的形式，需要通过链栈得到他的最终的虚拟路径
    // 然后和serverDir拼接得到最后的真正路径
    ServerVirtualPathStack *pstack = ServerVirtualPathStack_init();
    if(args_path[0] != '/') {
        // 说明参数路径是相对路径，需要使用虚拟当前目录
        pathTostack(pstack, vir_path);
    }
    // 将参数路径压入链栈
    pathTostack(pstack, args_path);
    bzero(vir_path, sizeof(vir_path));
    ServerVirtualPathStack_print(pstack, vir_path);
    bzero(truePath, sizeof(truePath));
    snprintf(truePath, sizeof(truePath), "%s%s", serverDir, vir_path);
    if(access(truePath, F_OK)) {
        // 当前文件不存在
        response.type = RES_ERR_2;
        response.vir_path_len = 0;
        strcpy(response.args_val, "目标文件不存在，请检查后重新输入正确路径!");
        response.args_len = strlen(response.args_val);
        send(netfd, &response.type, sizeof(response.type), MSG_NOSIGNAL);
        send(netfd, &response.vir_path_len, sizeof(int), MSG_NOSIGNAL);
        send(netfd, &response.args_len, sizeof(int), MSG_NOSIGNAL);
        send(netfd, response.args_val, response.args_len, MSG_NOSIGNAL);

        return 0;
    }
    ret = unlink(truePath);
    ERROR_CHECK(ret, -1, "unlink");
    response.type = RES_REMOVE;
    response.vir_path_len = 0;
    response.args_len = strlen(args_path);
    memcpy(response.args_val, args_path, response.args_len);
    send(netfd, &response.type, sizeof(response.type), MSG_NOSIGNAL);
    send(netfd, &response.vir_path_len, sizeof(int), MSG_NOSIGNAL);
    send(netfd, &response.args_len, sizeof(int), MSG_NOSIGNAL);
    send(netfd, response.args_val, response.args_len, MSG_NOSIGNAL);

    return 0;
}